import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { Dormitory } from './dormitory.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { CacheService } from 'src/cache/cache.service';
import { Cron } from '@nestjs/schedule';
import * as moment from "moment"
import { UserService } from 'src/user/user.service';
import { RoleEnum } from 'src/role/role.enum';
import { NoticeService } from 'src/notice/notice.service';

@Injectable()
export class DormitoryService {
    constructor(
        @InjectRepository(Dormitory)
        public readonly dormitory: Repository<Dormitory>,
        private readonly cacheService: CacheService,
        private readonly userService: UserService,
        private noticeService: NoticeService
    ) { }

    /**
     * 每天5点检查房租、物业费是否过期
     */
    @Cron("0 0 5 * * *")
    private async load() {
        const list = await this.dormitory.find({
            relations: ["system"]
        })
        for (const dormitory of list) {
            const { propertyDueDate, rentDueDate } = dormitory;
            if (!!propertyDueDate) this.isDue("物业费", moment(propertyDueDate), dormitory)
            if (!!rentDueDate) this.isDue("房租", moment(rentDueDate), dormitory)
        }
    }
    private async isDue(
        name: string,
        time: moment.Moment,
        dormitory: Dormitory
    ) {
        const bool = this.isWithinTenDaysBeforeDue(moment(), time);
        if (!bool) return;
        const users = await this.userService.userSys.find({
            where: [{
                system: { id: dormitory.system.id },
                dept: {
                    name: "行政部"
                }
            }, {
                system: { id: dormitory.system.id },
                role: RoleEnum.director
            }]
        })
        for (const user of users) {
            this.noticeService.create(user, null, "您有一条新的通知", `编号 ${dormitory.id} 的 ${name} 即将到期，请及时续费`)
        }
    }
    private isWithinTenDaysBeforeDue(current: moment.Moment, due: moment.Moment): boolean {
        const tenDaysBeforeDue = due.clone().subtract(10, 'days');
        return current.isSameOrAfter(tenDaysBeforeDue, 'day') && current.isBefore(due, 'day');
    }
}
